<template>
	<view class="container worker-index-container">
		<!-- 授权失败提示 -->
		<view v-if="showAuthError" class="auth-error-banner">
			<view class="auth-error-text">授权失败，部分功能可能无法正常使用</view>
			<view class="auth-retry-btn" @click="retryAuth">重新授权</view>
		</view>
		
		<view>
			<view class="page-list" @click="jump('/pages/writeOff/writeOff')">
				<image class="list-img" :src="$fileUrl+'worker-idx-1.png'" mode="widthFix"></image>
				<view class="list-title">核销助手</view>
				<view class="list-tips">99</view>
			</view>
			<view class="page-list" @click="jump('/pages/reservation/list')">
				<image class="list-img" :src="$fileUrl+'worker-idx-2.png'" mode="widthFix"></image>
				<view class="list-title">预约到店</view>
				<view class="list-tips list-tips-show">有 {{appointCount}} 条预约待处理</view>
			</view>
			<view class="page-list" @click="jump('/pages/patient/list')">
				<image class="list-img" :src="$fileUrl+'worker-idx-3.png'" mode="widthFix"></image>
				<view class="list-title">患者管理</view>
				<view class="list-tips">1</view>
			</view>
			<view class="page-list" @click="jump('/pages/worker/detail')">
				<image class="list-img" :src="$fileUrl+'worker-idx-4.png'" mode="widthFix"></image>
				<view class="list-title">个人信息</view>
				<view class="list-tips">1</view>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { onMounted, ref } from 'vue';
	import userApi from '@/common/userApi';
	import { hideLoading, showLoading, getOpenWxCode, goBack, getAuthError, clearAuthError, redirectToAuth, showToast, setStorage, getStorage } from '@/common/util';
	import { markCodeAsUsed } from '../../common/codeManager';
	import api from '../../common/api';
	const jump = (url : string) => {
		uni.navigateTo({ url: url })
	}
	
	onMounted(async () => {
		await handleAuth()
		//本地测试用
		// await back2Index('AEqSBuHZjlq5OA5fq6GAqMDWPTFfmZ3VF9POfA7A6xs') 
	})
	
	// 处理授权逻辑
	const handleAuth = async () => {
		// 检查是否有授权错误
		const authError = getAuthError()
		if (authError) {
			console.log('检测到授权错误:', authError)
			showAuthErrorDialog(authError)
			return
		}
		
		// 尝试获取授权码
		const code = getOpenWxCode()
		if (code) {
			// alert(code)
			back2Index(code)
		} else {
			// 如果没有code且没有错误，说明正在跳转授权页面
			console.log('正在跳转到授权页面...')
		}
	}
	
	// 显示授权错误对话框
	const showAuthErrorDialog = (authError: any) => {
		showAuthError.value = true // 显示错误横幅
		uni.showModal({
			title: '授权失败',
			content: `${authError.description || '用户拒绝授权'}，请重新授权以正常使用应用功能。`,
			confirmText: '重新授权',
			cancelText: '取消',
			success: (res) => {
				if (res.confirm) {
					// 用户点击重新授权
					retryAuth()
				} else {
					// 用户点击取消，可以显示提示或限制功能
					showToast('需要授权才能正常使用应用功能')
				}
			}
		})
	}
	
	// 重新授权
	const retryAuth = () => {
		showAuthError.value = false // 隐藏错误横幅
		clearAuthError() // 清除错误状态
		const code = getOpenWxCode(true) // 强制重新授权
		if (!code) {
			console.log('重新跳转到授权页面...')
		}
	}
	
	const back2Index = async (code: string) => {
		//等待后端接口
		if (code) {
			try {
				const res = await api.workshopAutoLogin(code)
				if(res && res.code == 801){
					// 授权失败，不标记 code 为已使用，可以重试
					return
				}else if(res && res.code == 205){
					// 需要跳转到其他页面，标记 code 为已使用
					markCodeAsUsed()
					uni.reLaunch({
						url:'/pages/public/wxcode'
					})
				}else{
					// 授权成功，标记 code 为已使用
					markCodeAsUsed()
					setStorage('userAuth',res.data)
					await getPageList()
				}
			} catch (error) {
				// 接口调用失败，不标记 code 为已使用，可以重试
				console.error('授权接口调用失败:', error)
			}
		}
	}
	const appointCount = ref(0)
	const showAuthError = ref(false)
	
	const getPageList = async () => {
		showLoading()
		try {
			const params = {
				pcUserId:getStorage('userAuth').pcUserId,
				pageNum: 1,
				pageSize: 2,
				status: 0,
			}
			const res = await userApi.getAppointments(params)
			appointCount.value = res.data.total
		} finally {
			hideLoading()
		}
	}
</script>


<style lang="scss">
	.worker-index-container {
		padding: 25rpx;
		background: linear-gradient(180deg, #DAFBFB 0%, #D7E5FF 8%, #F2F3F8 40%, #F2F3F8 100%);

		.auth-error-banner {
			background-color: #fff2f0;
			border: 1px solid #ffccc7;
			border-radius: 10rpx;
			padding: 20rpx;
			margin-bottom: 20rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.auth-error-text {
				color: #ff4d4f;
				font-size: 28rpx;
				flex: 1;
			}

			.auth-retry-btn {
				background-color: #ff4d4f;
				color: white;
				padding: 10rpx 20rpx;
				border-radius: 6rpx;
				font-size: 24rpx;
				margin-left: 20rpx;
			}
		}

		.page-list {
			display: inline-block;
			width: 48%;
			background-color: #fff;
			border-radius: 10rpx;
			margin-bottom: 20rpx;
			padding: 30rpx;
		}

		.page-list:nth-child(2n) {
			margin-left: 2%;
		}

		.list-img {
			width: 62rpx;
			height: 62rpx;
		}

		.list-title {
			font-size: 32rpx;
			color: #222222;
		}

		.list-tips {
			font-size: 24rpx;
			background-color: rgba(252, 74, 64, 0.20);
			color: #FC4A40;
			opacity: 0;
			margin-top: 15rpx;
			padding: 4rpx 10rpx;
			border-radius: 4rpx;
		}

		.list-tips-show {
			opacity: 1;
		}
	}
</style>